package com.example.a4_3;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_id;
    private EditText et_password;
    private Button btn_save;
    private Button btn_clear;
    private Button btn_load;
    private final String FN = "userInfo";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_id = (EditText) findViewById(R.id.et_id);
        et_password = (EditText) findViewById(R.id.et_password);
        btn_save = (Button) findViewById(R.id.btn_save);
        btn_clear = (Button) findViewById(R.id.btn_clear);
        btn_load = (Button) findViewById(R.id.btn_load);
        btn_save.setOnClickListener(this);
        btn_clear.setOnClickListener(this);
        btn_load.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save:
                String userName = et_id.getText().toString();
                String pwd = et_password.getText().toString();
                if ("".equals(userName) || "".equals(pwd)) {
                    Toast.makeText(MainActivity.this, "账号或密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                SharedPreferences sharedPreferences = getSharedPreferences(FN,
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("user_name", userName);
                editor.putString("password", pwd);
                editor.commit();
                break;
            case R.id.btn_clear:
                et_id.setText("");
                et_password.setText("");
                break;
            case R.id.btn_load:
                SharedPreferences sp = getSharedPreferences(FN, Context.MODE_PRIVATE);
                String us_name = sp.getString("user_name", "");
                String password = sp.getString("password", "");
                et_id.setText(us_name);
                et_password.setText(password);
                break;
            default:
                break;
        }
    }
}